#include "web_socket_server.hpp"

#include <boost/bind.hpp>
#include <iostream>

web_socket_server::web_socket_server(boost::asio::io_service& io_service,
                                     int port,
                                     boost::shared_ptr<logger> log,
                                     boost::shared_ptr<client_factory> factory,
                                     const std::string& origin,
                                     const std::string& location,
                                     boost::shared_ptr<message_receiver> receiver) :
    _new_client_index(0),
    _acceptor(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)),
    _logger(log),
    _client_factory(factory),
    _receiver(receiver),
    _handler(origin, location)
{
}

void web_socket_server::start_accept()
{
    boost::shared_ptr<client> new_client = _client_factory->create_client(_acceptor.get_io_service(), this, _logger, _new_client_index);
    _new_client_index++;

    _acceptor.async_accept(new_client->socket(), boost::bind(&web_socket_server::handle_accept, this, new_client, boost::asio::placeholders::error));
}

void web_socket_server::handle_accept(boost::shared_ptr<client> new_client, const boost::system::error_code& error)
{
    if (!error)
    {
        std::cout << "index: " << new_client->index() << std::endl;
        _clients[new_client->index()] = new_client;
        new_client->start();
        _logger->log(logger::info, new_client->socket().remote_endpoint().address().to_string() + std::string(" connected."));
        start_accept();
    }
}
